<script setup>
import { ref, onUnmounted } from 'vue'
import { sendSmsCodeApi } from '../../api/user'
import { showNoneIconToast, showSeccessToast } from '../../utils/toast'
import { useUserStore  } from '../../stores/modules/user'
import websocket from '../../utils/websocket'

const userStore = useUserStore()
// 响应式数据
const phone = ref('')
const verifyCode = ref('')
const countdown = ref(0)
let timer = null

// 手机号格式校验
const validatePhone = (phoneNumber) => {
	// 手机号正则表达式
	const phoneRegex = /^1[3-9]\d{9}$/
	
	if (!phoneNumber) {
		uni.showToast({
			title: '请输入手机号',
			icon: 'none'
		})
		return false
	}
	
	if (!phoneRegex.test(phoneNumber)) {
		uni.showToast({
			title: '请输入正确的手机号格式',
			icon: 'none'
		})
		return false
	}
	
	return true
}

// 获取验证码
const getVerifyCode = async () => {
	if (countdown.value > 0) return
	
	// 手机号格式校验
	if (!validatePhone(phone.value)) {
		return
	}
	
	uni.hideKeyboard()
	
	try {
		const res = await sendSmsCodeApi(phone.value)
		showSeccessToast("发送成功")
		
		countdown.value = 60
		timer = setInterval(() => {
			countdown.value--
			if (countdown.value <= 0) {
				clearInterval(timer)
			}
		}, 1000)
	} catch (error) {
		console.log(error);
	}
}

// 下一步
const nextStep = async () => {
	// 手机号格式校验
	if (!validatePhone(phone.value)) {
		return
	}
	
	if (!verifyCode.value) {
		showNoneIconToast("请输入验证码")
		return
	}
	
	// 验证码格式校验
	if (verifyCode.value.length !== 6) {
		showNoneIconToast("请输入6位验证码")
		return
	}
	
	// 关闭键盘
	uni.hideKeyboard()
	
	try {
		// 执行登录
		await userStore.loginByCodeAction({
			phone: phone.value,
			code: verifyCode.value
		})
		showSeccessToast("登录成功")
		
		// 获取用户信息
		await userStore.getUserInfoAction()

		// 根据用户角色决定跳转页面
		const userRole = userStore.userInfo?.role || 1
		let targetUrl = ''
		
		if (userRole === 2) {
			// role = 2，跳转到招聘者页面
			targetUrl = '/pages/company/recommend/recommend'
			userStore.setUserRole('company')
		} else {
			// role = 1 或其他，跳转到求职者页面
			targetUrl = '/pages/candidate/position/position'
			userStore.setUserRole('candidate')
		}
		
		// 保存角色状态
		uni.setStorageSync('currentRole', userStore.userRole)
		
		// 初始化WebSocket连接
		websocket.initSocketConnect()
		
		// 跳转到对应页面
		uni.reLaunch({
			url: targetUrl,
			success: () => {
				console.log('跳转成功，目标页面:', targetUrl)
			},
			fail: (err) => {
				console.error('跳转失败:', err)
			}
		})
	} catch (error) {
		console.error('登录失败:', error)
		showNoneIconToast("登录失败，请重试")
	}
}

// 页面卸载时清除定时器
onUnmounted(() => {
	if (timer) {
		clearInterval(timer)
	}
})
</script>
    
<template>
	<view class="page">
		<view class="login-box">
			<!-- 标题区域 -->
			<view class="header-section">
				<!-- 左侧文字部分 -->
				<view class="header-left">
					<view class="title">登录/注册</view>
					<view class="subtitle">首次验证通过即注册智聘账号</view>
				</view>
				
				<!-- 右侧logo -->
				<view class="header-right">
					<image class="logo" src="/static/images/logo.png" mode="aspectFit"></image>
				</view>
			</view>
			
			<!-- 表单区域 -->
			<view class="form-container">
				<!-- 手机号输入框 -->
				<view class="input-group">
					<view class="input-label">手机号</view>
					<view class="input-wrapper">
						<input 
							class="input-field"
							type="number"
							placeholder="请输入手机号"
							v-model="phone"
							maxlength="11"
							clearable
						/>
					</view>
				</view>
				
				<!-- 验证码输入框 -->
				<view class="input-group">
					<view class="input-label">验证码</view>
					<view class="verify-code-container">
						<view class="input-wrapper verify-input">
							<input 
								class="input-field"
								type="number"
								placeholder="请输入验证码"
								v-model="verifyCode"
								maxlength="6"
								clearable
							/>
						</view>
						<button 
							class="verify-btn"
							:class="{ 'disabled': countdown > 0 }"
							@click="getVerifyCode"
						>
							{{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
						</button>
					</view>
				</view>
				
				<!-- 下一步按钮 -->
				<button class="next-btn" @click="nextStep">
					下一步
				</button>
			</view>
		</view>
	</view>
</template>
    
<style scoped>
.page {
	position: absolute;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	background-color: #ffffff;
	padding: 20rpx;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	transform: translateZ(0);
	-webkit-transform: translateZ(0);
}

.login-box {
	display: flex;
	flex-direction: column;
	margin-top: 280rpx;
	padding: 20rpx;
	position: relative;
	z-index: 1;
}

.header-section {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	margin-bottom: 80rpx;
}

.header-left {
	flex: 1;
	margin-right: 40rpx;
}

.header-right {
	width: 200rpx;
	height: 200rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
}

.logo {
	width: 100%;
	height: 100%;
}

.title {
	font-size: 48rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 20rpx;
}

.subtitle {
	font-size: 28rpx;
	color: #666666;
}

.form-container {
	width: 100%;
}

.input-group {
	margin-bottom: 40rpx;
}

.input-label {
	font-size: 32rpx;
	color: #333333;
	margin-bottom: 20rpx;
	font-weight: 500;
}

.input-wrapper {
	background-color: #f8f8f8;
	border-radius: 12rpx;
	padding: 0 24rpx;
	height: 88rpx;
	display: flex;
	align-items: center;
	position: relative;
}

.input-field {
	flex: 1;
	height: 100%;
	font-size: 32rpx;
	color: #333333;
	position: relative;
	z-index: 2;
}

.verify-code-container {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.verify-input {
	flex: 1;
}

.verify-btn {
	width: 200rpx;
	height: 88rpx;
	background-color: #46b4b3;
	color: #ffffff;
	border-radius: 12rpx;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
}

.verify-btn.disabled {
	background-color: #cccccc;
	color: #999999;
}

.next-btn {
	width: 100%;
	height: 88rpx;
	background-color: #46b4b3;
	color: #ffffff;
	border-radius: 12rpx;
	font-size: 32rpx;
	font-weight: 500;
	margin-top: 60rpx;
	border: none;
}

.next-btn:active {
	background-color: #3a9a99;
}

/* 输入框占位符样式 */
.input-field::placeholder {
	color: #999999;
}
</style>